package com.snoopy.gas1.controller;

import com.snoopy.gas1.entity.Oil_info;
import com.snoopy.gas1.service.Oil_infoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/oil_info")
public class Oil_infoController {

    @Autowired
    private Oil_infoService oilInfoService;

    // 列表页面
    @GetMapping("/list")
    public String list(Model model) {
        List<Oil_info> oilLists = oilInfoService.lists();
        model.addAttribute("oilLists", oilLists);
        return "oil_info/list"; // 对应前端列表页面
    }

    // 搜索功能 - 修复页面跳转路径
    @GetMapping("/search")
    public String search(@RequestParam("name") String name, Model model) {
        List<Oil_info> oilLists = oilInfoService.searchByName(name);
        model.addAttribute("oilLists", oilLists);
        // 修复路径大小写问题，保持与类路径一致
        return "oil_info/list";
    }

    // 删除功能
    @GetMapping("/delete")
    public String delete(@RequestParam("id") int id) {
        oilInfoService.deleteById(id);
        return "redirect:/oil_info/list"; // 重定向到列表页
    }

    // 跳转到添加页面
    @GetMapping("/add")
    public String toAddPage() {
        return "oil_info/add";
    }

    // 保存添加数据
    @PostMapping("/save")
    public String save(Oil_info oilInfo, Model model) {
        try {
            int result = oilInfoService.add(oilInfo);
            if (result > 0) {
                return "redirect:/oil_info/list";
            } else {
                model.addAttribute("errorMsg", "添加失败，请重试");
                return "oil_info/add";
            }
        } catch (RuntimeException e) {
            model.addAttribute("errorMsg", e.getMessage());
            return "oil_info/add";
        }
    }

    // 跳转到编辑页面
    @GetMapping("/edit/{id}")
    public String toEditPage(@PathVariable("id") int id, Model model) {
        Oil_info oilInfo = oilInfoService.getById(id);
        model.addAttribute("oilInfo", oilInfo);
        return "oil_info/edit";
    }

    // 保存更新数据
    @PostMapping("/update")
    public String update(Oil_info oilInfo, Model model) {
        try {
            int result = oilInfoService.update(oilInfo);
            if (result > 0) {
                return "redirect:/oil_info/list";
            } else {
                model.addAttribute("errorMsg", "更新失败，请重试");
                model.addAttribute("oilInfo", oilInfo);
                return "oil_info/edit";
            }
        } catch (RuntimeException e) {
            model.addAttribute("errorMsg", e.getMessage());
            model.addAttribute("oilInfo", oilInfo);
            return "oil_info/edit";
        }
    }
}
